package com.programmingteam.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.programmingteam.wallpaperslideshow.Config;

public class HttpHelper {

	public String queryService(URI requestURI) throws URISyntaxException, ClientProtocolException, IOException {
		HttpParams httpParameters;
		HttpClient client;
		HttpGet request;
		HttpResponse response;
		String responseBody;
		ByteArrayOutputStream outputByteBuffer = null;

		try {
			httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters, Config.Http.TIMEOUT_CONNECTION);
			HttpConnectionParams.setSoTimeout(httpParameters, Config.Http.TIMEOUT_READ_TEXT);
			client = new DefaultHttpClient(httpParameters);
			request = new HttpGet();
			request.setURI(requestURI);
			response = client.execute(request);
			outputByteBuffer = new ByteArrayOutputStream(Config.Http.DOWNLOAD_BUFFER_SIZE);
			response.getEntity().writeTo(outputByteBuffer);
			responseBody = outputByteBuffer.toString();
		}
		finally {
			if (outputByteBuffer != null) {
				try {
					outputByteBuffer.close();
				}
				catch (IOException e) {}
			}
		}
		return responseBody;
	}
	
	public void downloadFile(final URI uri, final File outputFile) throws MalformedURLException, IOException {
		HttpURLConnection urlConnection = (HttpURLConnection) uri.toURL().openConnection();
		FileOutputStream fileOutput;
		InputStream inputStream;
		byte[] buffer;
		int bufferLength = 0;
		
		urlConnection.setConnectTimeout(Config.Http.TIMEOUT_CONNECTION);
		urlConnection.setReadTimeout(Config.Http.TIMEOUT_READ_FILE);
		urlConnection.setRequestMethod("GET");
		urlConnection.setDoOutput(true);
		urlConnection.connect();
		fileOutput = new FileOutputStream(outputFile);
		inputStream = urlConnection.getInputStream();
		buffer = new byte[Config.Http.DOWNLOAD_BUFFER_SIZE];
		while ((bufferLength = inputStream.read(buffer)) > 0) {
			fileOutput.write(buffer, 0, bufferLength);
		}
	}
}
